package com.weishao.dbmapper.engine;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import com.weishao.dbmapper.AbstractMapperEngine;
import com.weishao.dbmapper.IResultRowHandler;
import com.weishao.dbmapper.pojo.TaskMapTypeEnum;
import com.weishao.dbmapper.pojo.TaskParamEntity;

/**
 * 映射引擎实现类
 * 
 * @author tang
 *
 */
public class DefaultMapperEngine extends AbstractMapperEngine {

	private static Map<String, String> engines;

	static {
		engines = new HashMap<String, String>();
		engines.put(TaskMapTypeEnum.OneByOne.getEngineName(), "com.weishao.dbmapper.engine.impl.OneByOneMapperImpl");
		engines.put(TaskMapTypeEnum.MultiByOne.getEngineName(), "com.weishao.dbmapper.engine.impl.MultByOneMapperImpl");
	}

	@Override
	protected void handleTransfer(TaskParamEntity task, IResultRowHandler handler) {
		IMapperService mapper;
		String className = engines.get(task.getMapType().getEngineName());
		try {
			Class<?>[] paraTypes = { DataSource.class, int.class, boolean.class };
			Object[] paraValues = { this.dataSource, task.getFetchSize(), this.quiteWhenCoderMapperException };
			Class<?> clazz = Class.forName(className);
			Constructor<?> constructor = clazz.getConstructor(paraTypes);
			mapper = (IMapperService) constructor.newInstance(paraValues);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		mapper.mapper(task, handler);
	}

}